//
//  PeripheralViewController.m
//  bleIOSSdkDemo
//
//  Created by 董海伟 on 2019/2/9.
//  Copyright © 2019 董海伟. All rights reserved.
//

#import "PeripheralViewController.h"
#import "bleHeader.h"
#import "MBProgressHUD/MBProgressHUD+MoreExtensions.h"

@interface PeripheralViewController () <UITextFieldDelegate, UITextViewDelegate, bleIOSSdkDelegate>
@property(strong, nonatomic)  UILabel          *labelConStatus;
@property(strong, nonatomic)  UILabel          *labelDevName;
@property(assign, nonatomic)  bool              bConnect;
@property(assign, nonatomic)  CBCharacteristic *writecharacteristic;
@property(strong, nonatomic)  UITextField      *sendTextField;
@property(strong, nonatomic)  UIButton         *sendBtn;
@property(strong, nonatomic)  UIButton         *sendMoreBtn;
@property(strong, nonatomic)  UITextView       *recvTextView;
@property (strong, nonatomic) UILabel          *placeholderLabel;

@end

@implementation PeripheralViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    
    self.bConnect = false;
    
    self.labelConStatus = [[UILabel alloc] init];
    [self.labelConStatus setFrame: CGRectMake(0, 80, SCREEN_WIDTH, 30)];
    [self.labelConStatus setTextAlignment: NSTextAlignmentCenter];
    [self.labelConStatus setText: @"连接成功！"];
    [self.labelConStatus setFont: [UIFont systemFontOfSize:18]];
    [self.labelConStatus setTextColor: [UIColor blackColor]];
    [self.labelConStatus setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:self.labelConStatus];
    [self.labelConStatus setHidden: true];
    
    self.labelDevName = [[UILabel alloc] init];
    [self.labelDevName setFrame: CGRectMake(0, 110, SCREEN_WIDTH, 30)];
    [self.labelDevName setTextAlignment: NSTextAlignmentCenter];
    NSString *devName = [NSString stringWithFormat:@"设备名称:%@", self.currPeripheral.name];
    [self.labelDevName setText: devName];
    [self.labelDevName setFont: [UIFont systemFontOfSize:18]];
    [self.labelDevName setTextColor: [UIColor blackColor]];
    [self.labelDevName setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:self.labelDevName];
    [self.labelDevName setHidden: true];
    
    self.sendTextField = [[UITextField alloc] init];
    [self.sendTextField setFrame: CGRectMake(30, 150, SCREEN_WIDTH-60, 40)];
    [self.sendTextField setPlaceholder:@"发送数据"];
    self.sendTextField.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:self.sendTextField];
    [self.sendTextField setHidden: true];
    self.sendTextField.delegate =self;
    
    self.sendBtn = [[UIButton alloc] init];
    [self.sendBtn setFrame: CGRectMake(30, 200, SCREEN_WIDTH-60, 40)];
    [self.sendBtn setTitle: @"发送" forState: UIControlStateNormal];
    [self.sendBtn setTitleColor: [UIColor whiteColor] forState: UIControlStateNormal];
    [self.view addSubview:self.sendBtn];
    [self.sendBtn setHidden: true];
    [self.sendBtn setBackgroundColor: mRGBColor(135,206,250)];
    //设置圆角的半径
    [self.sendBtn.layer setCornerRadius:5];
    //切割超出圆角范围的子视图
    self.sendBtn.layer.masksToBounds = YES;
    [self.sendBtn addTarget: self action: @selector(actionSendText:) forControlEvents:UIControlEventTouchUpInside];
    
    self.sendMoreBtn = [[UIButton alloc] init];
    [self.sendMoreBtn setFrame: CGRectMake(30, 500, SCREEN_WIDTH-60, 40)];
    [self.sendMoreBtn setTitle: @"发送10K" forState: UIControlStateNormal];
    [self.sendMoreBtn setTitleColor: [UIColor whiteColor] forState: UIControlStateNormal];
    [self.view addSubview:self.sendMoreBtn];
    [self.sendMoreBtn setHidden: true];
    [self.sendMoreBtn setBackgroundColor: mRGBColor(135,206,250)];
    //设置圆角的半径
    [self.sendMoreBtn.layer setCornerRadius:5];
    //切割超出圆角范围的子视图
    self.sendMoreBtn.layer.masksToBounds = YES;
    [self.sendMoreBtn addTarget: self action: @selector(actionSendMoreText:) forControlEvents:UIControlEventTouchUpInside];
    
    self.recvTextView = [[UITextView alloc] init];
    [self.recvTextView setFrame: CGRectMake(30, 260, SCREEN_WIDTH-60, 220)];
    self.recvTextView.backgroundColor=[UIColor whiteColor];
    self.recvTextView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.recvTextView.layer.borderWidth = 0.6f;
    self.recvTextView.layer.cornerRadius = 6;
    self.recvTextView.layer.masksToBounds = YES;
    self.recvTextView.clipsToBounds = YES;
    [self.view addSubview:self.recvTextView];
    [self.recvTextView setHidden: true];
    self.recvTextView.delegate = self;
    [self.recvTextView setEditable: NO];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidChange:) name:UITextViewTextDidChangeNotification object:nil];
    
    self.placeholderLabel = [[UILabel alloc] init];
    [self.placeholderLabel setFrame: CGRectMake(3, 0, 120, 30)];
    [self.placeholderLabel setTextAlignment: NSTextAlignmentLeft];
    [self.placeholderLabel setText: @"接收数据..."];
    [self.placeholderLabel setFont: [UIFont systemFontOfSize:14]];
    [self.placeholderLabel setTextColor: [UIColor lightGrayColor]];
    [self.placeholderLabel setBackgroundColor:[UIColor clearColor]];
    [self.recvTextView addSubview:self.placeholderLabel];
    [self.placeholderLabel setHidden: true];
    
    [self.bleSdk setDelegate: self];
    [self.bleSdk connectDevice: self.currPeripheral];
    [MBProgressHUD showTipHUDAddedTo:self.view WithLabel:@"开始连接设备"];
}

-(void) dealloc{
    if (self.bConnect) {
        [self.baby setBlockOnDisconnect:nil];
        
        [self.baby cancelPeripheralConnection: self.currPeripheral];
        self.bConnect = false;
    }
}

- (BOOL) textFieldShouldReturn: (UITextField *) textField{
    [self.sendTextField resignFirstResponder];
    
    [self actionSendText: nil];
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES]; //实现该方法是需要注意view需要是继承UIControl而来的
}

-(void) actionSendText: (UIButton *) btn {
    NSString *sendText = self.sendTextField.text;
    if(nil != sendText && [sendText length] > 0) {
        [self.bleSdk sendData: [sendText dataUsingEncoding:NSUTF8StringEncoding] withTid:1 withSid:2];
        
        //for test
        /*
        [self.currPeripheral writeValue: [bleIOSSdk converHexStrToData:sendText] forCharacteristic:self.writecharacteristic type: CBCharacteristicWriteWithoutResponse];
        */
        [self.sendTextField resignFirstResponder];
    }
}

-(void) actionSendMoreText: (UIButton *) btn {
    int len=10240;
    char *sendBigBuf = new char[len];
    int j=0;
    for (int i=0; i<len; ++i) {
        sendBigBuf[i]=j++;
        if(j==10) {
            j=0;
        }
    }
    
    [self.bleSdk sendData: [NSData dataWithBytes: sendBigBuf length:len] withTid:1 withSid:2];
    [self.sendTextField resignFirstResponder];
    
    delete [] sendBigBuf;
    sendBigBuf=NULL;
}

-(void) setRecvTextViewText: (NSString *) str {
    [self.recvTextView setText: str];
    [self textViewDidChange: self.recvTextView];
}

-(void) textViewDidChange: (UITextView *) textView {
    if ([self.recvTextView.text isEqualToString:@""]){
        self.placeholderLabel.hidden = NO;
    }else{
        self.placeholderLabel.hidden = YES;
    }
}

#pragma ---bleIOSSdkDelegate
-(void)onConnec: (int) retCode {
    if ( ERR_SUCCESS == retCode ) {
        [MBProgressHUD showTipHUDAddedTo:self.view WithLabel:[NSString stringWithFormat:@"设备：%@--连接成功", self.currPeripheral.name]];
        
        [self.labelConStatus setHidden: false];
        [self.labelDevName setHidden: false];
        [self.sendTextField setHidden: false];
        [self.recvTextView setHidden: false];
        [self.placeholderLabel setHidden: false];
        
        self.bConnect = true;
    } else if ( ERR_FAILED == retCode ) {
        [MBProgressHUD showTipHUDAddedTo:self.view WithLabel:[NSString stringWithFormat:@"设备：%@--连接失败",self.currPeripheral.name]];
        
        //返回
        [self.navigationController popViewControllerAnimated:YES];
        self.bConnect = false;
    } else if( ERR_CAN_SENDDATA == retCode ) {
        [self.sendBtn setHidden: false];
        [self.sendMoreBtn setHidden: false];
    }
}

-(void)onSendDataResult:(int)retCode with:(DataInfoOC*)dataInfoOC {
    NSLog(@"onSendDataResult retCode:%d dataLen:%d taskId:%d storeId:%d", retCode, [dataInfoOC dataLen], [dataInfoOC taskId], [dataInfoOC storeId]);
}

-(void)onRecvBleData:(NSData*) businessData with:(DataInfoOC*)dataInfoOC {
    NSLog(@"onSendDataResult businessData:%@ dataLen:%d taskId:%c storeId:%c", businessData, [dataInfoOC dataLen], [dataInfoOC taskId], [dataInfoOC storeId]);
    
    NSString *businessStr = [[NSString alloc] initWithData:businessData encoding:NSUTF8StringEncoding];
    NSLog(@"onRecvBleData str:%@", businessStr);
    
    NSString *outputStr = [NSString stringWithFormat:@"[recv] taskid=1,storeid=1,%@", businessStr];
    [self setRecvTextViewText: outputStr];
}

@end

